package ch10.demo.cn.cvs.controller;

import ch10.demo.cn.cvs.entity.PageSupport;
import ch10.demo.cn.cvs.entity.SysRole;
import ch10.demo.cn.cvs.entity.SysUser;
import ch10.demo.cn.cvs.service.SysRoleService;
import ch10.demo.cn.cvs.service.SysUserService;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class SysUserController {
    private Logger logger = Logger.getLogger(SysUserController.class);

    private SysUserService sysUserService;

    private SysRoleService sysRoleService;
    //跳转到登入页面
    @RequestMapping(value = "/toLogin")
    public String login() {
        logger.debug("跳转到登入页面");
        return "login";
    }

    //登录
    @PostMapping("/login")
    public String doLogin(HttpServletRequest request, HttpSession session, @RequestParam String account, @RequestParam String password) {
        logger.debug("登录方法");
//调用service方法，进行用户匹配
        SysUser sysUser = sysUserService.login(account, password);
        if (null != sysUser) {
            session.setAttribute("sysUser",sysUser);
            //登入成功，重定向到/user/toMain接口
            return "redirect:/user/toMain";
        } else {
            request.setAttribute("error", "用户名或密码不正确");
            return "login";
        }
    }

    //跳转到首页
    @RequestMapping("/toMain")
    public String main(HttpSession session) {
        if(session.getAttribute("sysUser")==null){
            return "redirect:/user/toLogin";
        }
        return "frame";
    }

    private ArrayList<SysUser> sysUsersList = new ArrayList<SysUser>();
    //    用于返回查询到的用户数据
    private ArrayList<SysUser> queryUserList = new ArrayList<SysUser>();

    public SysUserController() {
        try {
            sysUsersList.add(new SysUser(51, "zhaojing", "赵4静", "5555555", 1,
                    "13052654152", "上海市", 1, 1, new Date(), 1, new Date()));
            sysUsersList.add(new SysUser(41, "zhaojing", "赵5静", "5555555", 1,
                    "13052654152", "上海市", 1, 1, new Date(), 1, new Date()));
            sysUsersList.add(new SysUser(31, "zhaojing", "赵6静", "5555555", 1,
                    "13052654152", "上海市", 1, 1, new Date(), 1, new Date()));
            sysUsersList.add(new SysUser(21, "zhaojing", "赵6静", "5555555", 1,
                    "13052654152", "上海市", 1, 1, new Date(), 1, new Date()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //查询所有用户
    @GetMapping("/list")
    public String list(Model model) {
        logger.info("当查询条件为空时，查询用户信息");
        queryUserList.clear();
        queryUserList.addAll(sysUsersList);
        model.addAttribute("queryUserList", queryUserList);
        return "sysUser/sysUserList";
    }

    //    根据条件查询部分用户
    @PostMapping("/list")
    public String list(@RequestParam(value = "realName", required = false) String realName, Model model) {
        logger.info("查询条件:【realName】=" + realName + ",查询用户信息");
        queryUserList.clear();
        if (realName != null && !realName.equals("")) {
            for (SysUser user : sysUsersList) {
                if (user.getRealName().indexOf(realName) != -1) {
                    queryUserList.add(user);
                }
            }
        } else {
            queryUserList.addAll(sysUsersList);
        }
        model.addAttribute("queryUserList", queryUserList);
        return "sysUser/sysUserList";
    }

    //捕获异常信息，跳转到error页面
    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e, HttpServletRequest req) {
        req.setAttribute("e", e);
        return "error";
    }

    //一个抛出异常的接口
    @RequestMapping("/exLogin")
    public String exLogin(@RequestParam String account, @RequestParam String password) {
        SysUser user = sysUserService.login(account, password);
        if (null == user) {
            throw new RuntimeException("用户名或者密码不正确！");
        }
        return "redirect:/user/toMain";
    }
@GetMapping("/list")
    public String getUserList(Model model, String queryRealName, Integer queryRoledId, @RequestParam(defaultValue = "1") Integer pageIndex) {
        List<SysUser> userList = null;
        try {
            //设置页面内容
            int pageSize = 5;
//            总数量
            int totalCount = sysUserService.getUserCount(queryRealName, queryRoledId);
            //总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPlageCount = pages.getTotalPageCount();
            //控制首页和尾页
            if(pageIndex>totalPlageCount){
                pageIndex=totalPlageCount;
                throw new RuntimeException("页码不正确");
            }
            userList=sysUserService.getUserList(queryRealName,queryRoledId,pageIndex,pageSize);
            model.addAttribute("userList",userList);
            List<SysRole> roleList=null;
            roleList= sysRoleService.getRoleList();
            model.addAttribute("roleList", roleList);
            model.addAttribute("queryRealName", queryRealName);
            model.addAttribute("queryRoleId", queryRoledId);
            model.addAttribute("totalPlageCount", totalPlageCount);
            model.addAttribute("totalCount", totalCount);
            model.addAttribute("pageIndex", pageIndex);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户列表接口访问失败");
            return "redirect:/user/toSysError";
        }
        return "sysUser/list";
    }
    //跳转到异常处理页面
    @RequestMapping(value = "/toSysError")
    public String sysError(){
        return "sysError";
    }
}